$(function () {
    var query = {},users=[],
        $update = $('.btn-update'),
        $delete = $('.btn-delete'),
        $create = $('.btn-create'),
        $createAdmin =$('.btn-create-admin'),
        strHtml = $('#form-template').html(),
    strHtml1 = $('#com-create-admin').html();
    var config = {
        query: '/com/query?',//分页查询URL,
        create: '/com/create',//create,
        update: '/com/update',
        'delete': '/com/delete',
        user: '/user/query',
        role_update: '/user/role_update',
    };
    function getUsers() {
        var dtd = $.Deferred();
        if (users.length) {
            dtd.resolve(users);
        } else {
            $.get(config.user, function (data) {
                if (data.code == 200) {
                    users = data.list;
                    dtd.resolve(data.list)
                } else {
                    data.reject(data.error);
                }
            });
        }
        return dtd.promise();
    }
    function search(obj, isForce) {
        var query_ = {};
        $.extend(query_, query, obj instanceof Object ? obj : {});
        $loading.fadeIn();
        var arg = [];
        if (!isForce) {
            if (isSameQueryStr(query_, query)) { //查询条件和上次一样，取消请求
                return $loading.fadeOut();
            }
        }
        var arg = [];
        query = query_;
        query.timestamp = Date.now();
        Object.keys(query_).map(function (key) {
            arg.push(key + '=' + query_[key])
        });
        $.get(config.query + arg.join('&'), function (res) {
            var _$table = $('.table-responsive .table');
            destroyBtn();
            _$table.$table($.extend(TABLE_SETTING, {
                checkbox: true, // 是否显示复选框
                seqNum: true, // 是否显示序号
                sort: search, //排序回调函数
                destroyBtn: destroyBtn, //禁用按钮
                createBtn: createBtn, // 启用她扭
                toolbar: '.toolbar',
                enableSetting: true,//允许自定义显示列
                search: function (obj) { //搜索框查询函数
                    search(obj)
                },
                fields: [
                    {name: 'id', label: '单位ID'},
                    {name: 'name', _sort: 'name', label: '单位名称', enableSort: true, enableSearch: true},
                    {name: 'tel', _sort: 'tel', label: '电话', enableSort: true, enableSearch: true},
                    {name: 'fax', _sort: 'fax', label: '传真'},
                    {name: 'address', _sort: 'address', label: '地址'},
                    {name: 'bank', _sort: 'bank', label: '开户行'},
                    {name: 'bankAccount', _sort: 'bankAccount', label: '开户行账号'},
                    {name: 'taxNum', _sort: 'taxNum', label: '税号'},
                ],
                data: res.list || [],
            }));
            var page = res.page;
            pageInit(page, query, search);
        });
    }
    onClick($createAdmin, function () {
        var $current = $(this).data('json');

        $.when(getUsers())
            .done(function (users) {
                $current.users = users;
                var $modal = layerAlert({
                    title: '增加管理员',
                    full: true,
                    body: ejs.render(strHtml1, $current),
                    shown: function () {
                        validate1($modal);
                    },
                });
            })
            .fail(function (e) {
                console.log(e)
            })
    });

    $update.unbind('click').on('click', function () {
        var $current = $(this).data('json'), self = this;
        var $modal = layerAlert({
            title: '修改单位"' + $current.name + '"',
            full: true,
            body: ejs.render(strHtml, $current),
            shown: function () {
                validate($modal);
            },
        });
    });
    $delete.unbind('click').on('click', function () {
        var $current = $(this).data('json'), self = this;
        $(self).button('loading');
        if (confirm('确认删除"' + $(this).data('json').name + '"?')) {
            $.post(config['delete'], {id: $current.id}, function (xhr, data) {
                $(self).button('reset');
                if (xhr.code == 200) {
                    fnSuccess('删除成功!');
                    $('tr[id=' + $current.id + ']').remove();
                    // $(self).closest('tr').remove();
                    setTimeout(function () {
                        destroyBtn();
                    }, 0)
                } else {
                    alert('删除失败：' + xhr.error);
                }
            })
        } else {
            $(self).button('reset');
        }
    });
    $create.unbind('click').on('click', function () {
        var $modal = layerAlert({
            title: '新建单位',
            full:true,
            body: ejs.render(strHtml, {name: ''}),
            shown: function () {
                validate($modal);
            }
        })
    });

    function destroyBtn() {
        $update.data('json', null);
        $delete.data('json', null);
        $createAdmin.data('json',null);
        disableBtn($update);
        disableBtn($delete);
        disableBtn($createAdmin);
    }

    function createBtn(_this) {
        destroyBtn();
        $update.data('json', ($(_this).data('json')));
        $delete.data('json', ($(_this).data('json')));
        $createAdmin.data('json', ($(_this).data('json')));
        enableBtn($createAdmin);
        enableBtn($update);
        enableBtn($delete);
    }

    search({}, true);
    function validate(modal) {
        $('#registrationForm')
            .formValidation('destroy').formValidation($.extend({}, VALIDATION_SETTING, {
            fields: {
                name: {
                    row: '.col-xs-7',
                    validators: {
                        notEmpty: {
                            message: '单位名称必填'
                        },
                        stringLength: {
                            min: 3,
                            max: 40,
                            message: '单位名称长度最少3位，最多40位'
                        },
                    }
                },
                tel: {
                    row: '.col-xs-7',
                    validators: {
                        notEmpty: {
                            message: '必填'
                        },
                        phone: {
                            country: 'CN',
                            // message:'请输入正确电话'
                        }
                    }
                },
                fax: {
                    row: '.col-xs-7',
                    validators: {}
                },
                address: {
                    row: '.col-xs-7',
                    validators: {}
                },
                bank: {
                    row: '.col-xs-7',
                    validators: {}
                },
                bankAccount: {
                    row: '.col-xs-7',
                    validators: {}
                },
                texNum: {
                    row: '.col-xs-7',
                    validators: {}
                }
            }
        }))
            .off('success.form.fv').on('success.form.fv', function (e) {
            e.preventDefault();
            var form = parseSearch($(e.target).serialize());
            var url = '';
            if (form.id) { // is update?
                url = config.update;
            } else {
                url = config.create;
                delete form.id;
            }
            if (form.name) {
                form.name = form.name.trim();
            }
            $.post(url, form, function (xhr, data) {
                if (xhr.code == 200) {
                    // closeLayer(modal);
                    layer.closeAll();
                    fnSuccess(form.id ? '保存成功' : '创建成功!');
                    search({}, true);
                    //modal && modal.modal('hide');
                } else {
                    alert(xhr.error || xhr.msg);
                }
            });

        });
    }
    function validate1(modal) {
        $('#registrationForm1')
            .formValidation('destroy').formValidation($.extend({}, VALIDATION_SETTING, {
            fields: {

                name: {
                    row: '.col-xs-7',
                    validators: {
                        notEmpty: {
                            message: '姓名'
                        },
                        stringLength: {
                            min: 2,
                            max: 40,
                            message: '姓名长度最少2位，最多10位'
                        },
                    }
                },
                userName: {
                    row: '.col-xs-7',
                    validators: {
                        notEmpty: {
                            message: '必填'
                        },
                    }
                },
                phone: {
                    row: '.col-xs-7',
                    validators: {
                        notEmpty: {
                            message: '必填'
                        },
                        phone: {
                            country: 'CN',
                            // message:'请输入正确电话'
                        }
                    }
                },
                gender: {
                    row: '.col-xs-7',
                    validators: {
                        notEmpty: {
                            message: '必填'
                        },
                    }
                },
                qq: {
                    row: '.col-xs-7',
                    validators: {}
                },

            }
        }))
            .off('success.form.fv').on('success.form.fv', function (e) {
            e.preventDefault();
            var form = parseSearch($(e.target).serialize());
            var url = '/user/create';
            var obj = LS.json('MANAGER_CURRENT');
            ;
            if (form.name) {
                form.name = form.name.trim();
            }
            form.password = md5('123456');
            form.comid=form.sysId;
            if(obj.comid == 0&& obj.sysId == 0){
                form.comid = obj.comid
            }else{
                form.comid=form.sysId; // 此处固定

            }
            form.isAdmin = 1;//标记为管理员用户
            $.post(url, form, function (xhr, data) {
                if (xhr.code == 200) {
                    layer.closeAll();
                    fnSuccess(form.id ? '保存成功' : '创建成功!');
                    search({}, true);
                    //modal && modal.modal('hide');
                } else {
                    alert(xhr.error || xhr.msg);
                }
            });
        });
    }
});